﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace Swagger
{
    public static class JwtHelper
    {
        public static string Encrypt(string payload, string signKey)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signKey));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            JsonWebTokenHandler handler = new JsonWebTokenHandler();
            string token = handler.CreateToken(payload, credentials);
            return token;
        }

        /// <summary>
        /// 自定义认证
        /// </summary>
        /// <param name="services"></param>
        public static void AddRenZheng(this IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                //.AddAuthentication(o =>
                //{
                //    o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                //    o.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                //})
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        // 设置签发方
                        ValidIssuer = "22",
                        // 验证签发方
                        ValidateIssuer = false,
                        // 设置接收方
                        ValidAudience = "111",
                        // 验证接收方
                        ValidateAudience = false,

                        // 验证生存期
                        ValidateLifetime = false,
                        // 过期时间容错值
                        ClockSkew = TimeSpan.FromSeconds(2),
                        //RequireExpirationTime = true,

                        // 验证签发方密钥
                        ValidateIssuerSigningKey = true,
                        // 签发方密钥
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("123456789123456789123456789123456789"))
                    };
                    //options.Events = new JwtBearerEvents()
                    //{
                    //    OnAuthenticationFailed = context =>
                    //    {
                    //        // 如果过期，则把<是否过期>添加到，返回头信息中
                    //        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                    //        {
                    //            context.Response.Headers.Add("Token", "renzhengguoqi");
                    //        }
                    //        return Task.CompletedTask;
                    //    }
                    //};
                });
        }
    }
}
